import React, { useEffect, useRef, useState } from "react"
import Taro, { useDidShow } from "@tarojs/taro"
import { Button, Input, Picker, Text, View } from "@tarojs/components"
import { AtIcon } from "taro-ui"
import "./index.scss"
import http from "../../utils/http"
import PriceDetail from "../../components/price-detail"
import SubmitDetail from "./components/submitDetail"

const serviceCode = "CODE_SERVICE_CHARGE"

export default function () {
  // 初始值null 否则有个动画
  const [showPriceDetail, setShowPriceDetail] = useState(null)
  const [defaultPhone, setDefaultPhone] = useState("")
  const [defaultName, setDefaultName] = useState("")
  const [defaultRemark, setDefaultRemark] = useState("")
  const [RACKET_BRAND, setRACKET_BRAND] = useState([])
  const [selected_RACKET_BRAND, setSelected_RACKET_BRAND] = useState(null)
  const [showRACKET_BRAND, setShowRACKET_BRAND] = useState(true)
  const [LINE_TYPE, setLINE_TYPE] = useState([])
  const [selected_LINE_TYPE, setSelected_LINE_TYPE] = useState(null)
  const [showLINE_TYPE, setShowLINE_TYPE] = useState(true)
  const [LINE_POUND, setLINE_POUND] = useState([])
  const [selected_LINE_POUND, setSelected_LINE_POUND] = useState(null)
  const [showLINE_POUND, setShowLINE_POUND] = useState(true)
  const [THREADING_TYPE, setTHREADING_TYPE] = useState([])
  const [selected_THREADING_TYPE, setSelected_THREADING_TYPE] = useState(null)
  const [showTHREADING_TYPE, setShowTHREADING_TYPE] = useState(true)
  const [price, setPrice] = useState(0)
  const [servicePrice, setServicePrice] = useState(0)
  const [configPrice, setConfigPrice] = useState(0)
  const [date, setDate] = useState(null)
  const phoneRef = useRef()
  const nameRef = useRef()
  const remarkRef = useRef()
  const ticketId = Taro.getCurrentInstance().router.params?.id
  const [showSubmitDetail, setShowSubmitDetail] = useState(false)

  const getParams = () => {
    const params = {
      phone: phoneRef.current.props.value || "",
      linePound: selected_LINE_POUND?.dictLabel,
      price: (servicePrice * 100 + price * 100) / 100,
      extra:
        servicePrice != 0
          ? JSON.stringify([{ key: "CODE_SERVICE_CHARGE", name: "服务费", value: servicePrice }])
          : null,
      linePrice: price || 0,
      racketBrand: selected_RACKET_BRAND?.dictLabel,
      threadingType: selected_THREADING_TYPE?.dictLabel,
      userName: nameRef.current.props.value || "",
      userRemark: remarkRef.current.props.value || "",
      takeRacketTime: new Date(date).getTime(),
    }
    if (selected_THREADING_TYPE && selected_THREADING_TYPE.dictLabel === "自带") {
    } else {
      params.lineType = selected_LINE_TYPE?.dictLabel || ""
    }
    return params
  }

  const checkSubmitData = () => {
    const params = getParams()
    // 校验手机号规则
    const phoneReg = /^1[3456789]\d{9}$/
    if (!phoneReg.test(params.phone)) {
      Taro.showToast({
        title: "手机号格式不正确",
        icon: "none",
      })
      return
    }
    for (const key in params) {
      if (key === "lineType" && params.threadingType === "自带") {
      } else {
        if (key !== "userRemark" && key !== "extra" && key !== "linePrice") {
          if (params.hasOwnProperty(key)) {
            const element = params[key]
            if (!element) {
              Taro.showToast({
                title: "请填写完整信息",
                icon: "none",
              })
              return
            }
          }
        }
      }
    }
    setShowSubmitDetail(true)
  }

  const onSubmit = async () => {
    const params = getParams()
    if (ticketId) {
      params.ticketId = ticketId
      console.log("-ticketId-" + ticketId);
    }
    try {
      const url = ticketId ? "/core/ticket/update" : "/core/ticket/create"
      await http.post(url, params)
      console.log("====="+params.ticketId);
      Taro.showToast({
        title: ticketId ? "修改成功": "预约成功",
        icon: "success",
      })
      setTimeout(() => {
        Taro.redirectTo({
          url: "/pages/order/index",
        })
      }, 1500)
    } catch (e) {
      Taro.showToast({
        title: "预约失败，请重试",
        icon: "success",
      })
    }
  }

  const getConfig = async () => {
    Taro.showLoading()
    const { data } = await http.post("/core/config/data/search", { id: "0" })
    if (data) {
      setRACKET_BRAND(data.RACKET_BRAND)
      setLINE_TYPE(data.LINE_TYPE)
      setLINE_POUND(data.LINE_POUND)
      setTHREADING_TYPE(data.THREADING_TYPE)
      if (Taro.getCurrentInstance().router.params.id) {
        const { data: data2 } = await http.get(`/core/ticket/search/${Taro.getCurrentInstance().router.params.id}`)
        if (data2) {
          setDefaultPhone(data2.phone)
          setDefaultName(data2.userName)
          setDefaultRemark(data2.userRemark)
          setSelected_RACKET_BRAND(data.RACKET_BRAND.find(item => item.dictLabel === data2.racketBrand))
          setSelected_LINE_TYPE(data.LINE_TYPE.find(item => item.dictLabel === data2.lineType))
          setSelected_LINE_POUND(data.LINE_POUND.find(item => item.dictLabel === data2.linePound))
          setSelected_THREADING_TYPE(data.THREADING_TYPE.find(item => item.dictLabel === data2.threadingType))
          setDate(data2.takeRacketTime)
        }
      }
    }
    Taro.hideLoading()
  }

  const getPrice = async () => {
    const { data } = await http.post("/core/config/data/search", { dictType: "EXTRA_CHARGE" })
    if (data?.EXTRA_CHARGE) {
      setConfigPrice(Number(data?.EXTRA_CHARGE.find(item => item.dictCode === serviceCode).dictValue))
    }
  }

  const onGetPhoneNumber = async e => {
    const code = e.detail?.code
    if (e.detail.code) {
      const { data } = await http.post("/core/user/getUserPhoneNumber", { code })
      setDefaultPhone(data)
    }
  }

  const onMounted = () => {
    getConfig()
    getPrice()
  }

  useEffect(() => {
    onMounted()
  }, [])

  useEffect(() => {
    if (selected_THREADING_TYPE?.dictCode === "CODE_BUY") {
      setPrice(Number(selected_LINE_TYPE?.dictValue || 0))
      setServicePrice(0)
    } else if (selected_THREADING_TYPE?.dictCode === "CODE_BRING") {
      setPrice(0)
      setServicePrice(configPrice)
    }
  }, [selected_LINE_TYPE, selected_THREADING_TYPE])

  return (
    <View className={`page-appointment ${showSubmitDetail ? "scroll-disabled" : ""}`}>
      <View className="title">详细信息</View>
      <View className="detail">
        {/* 手机号码 */}
        <View className="row">
          <View className="row-main">
            <View className="label">手机号码</View>
            <Input
              ref={phoneRef}
              placeholderStyle="color: #BBBBBB;"
              placeholder="请输入手机号码"
              className="value"
              type="number"
              value={defaultPhone}
              onBlur={e => setDefaultPhone(e.detail.value)}
            ></Input>
            <Button className="get-phone" openType="getPhoneNumber" onGetPhoneNumber={e => onGetPhoneNumber(e)}>
              授权快速填入
            </Button>
          </View>
        </View>
        {/* 姓名 */}
        <View className="row">
          <View className="row-main">
            <View className="label">姓名</View>
            <Input
              ref={nameRef}
              value={defaultName}
              placeholder="请输入姓名"
              placeholderStyle="color: #BBBBBB;"
              className="value"
              onBlur={e => setDefaultName(e.detail.value)}
            ></Input>
          </View>
        </View>
        {/* 选择器 */}
        <View className="row">
          <View className="row-main" onClick={() => setShowRACKET_BRAND(!showRACKET_BRAND)}>
            <View className="label">球拍品牌</View>
            <View className="value">{selected_RACKET_BRAND?.dictLabel || "选择球拍品牌"}</View>
            <AtIcon value={!showRACKET_BRAND ? "chevron-down" : "chevron-right"} size={16}></AtIcon>
          </View>
          <View className={`row-select-list ${showRACKET_BRAND ? "row-select-show" : ""}`}>
            {RACKET_BRAND.map(item => (
              <View
                className={`select-item ${
                  item.dictLabel === selected_RACKET_BRAND?.dictLabel ? "select-item-active" : ""
                }`}
                key={item.dictLabel}
                onClick={() => setSelected_RACKET_BRAND(item)}
              >
                {item.dictLabel}
              </View>
            ))}
          </View>
        </View>
        <View className="row">
          <View className="row-main" onClick={() => setShowTHREADING_TYPE(!showTHREADING_TYPE)}>
            <View className="label">穿线类型</View>
            <View className="value">{selected_THREADING_TYPE?.dictLabel || "是否需要购买球线"}</View>
            <AtIcon value={!showTHREADING_TYPE ? "chevron-down" : "chevron-right"} size={16}></AtIcon>
          </View>
          <View className={`row-select-list ${showTHREADING_TYPE ? "row-select-show" : ""}`}>
            {THREADING_TYPE.map(item => (
              <View
                className={`select-item ${
                  item.dictLabel === selected_THREADING_TYPE?.dictLabel ? "select-item-active" : ""
                }`}
                key={item.dictLabel}
                onClick={() => {
                  setSelected_THREADING_TYPE(item)
                  if (item.dictCode !== "CODE_BRING") {
                    setShowLINE_TYPE(false)
                  }
                }}
              >
                {item.dictLabel}
              </View>
            ))}
          </View>
        </View>
        {selected_THREADING_TYPE?.dictCode === "CODE_BUY" && (
          <View className="row">
            <View className="row-main" onClick={() => setShowLINE_TYPE(!showLINE_TYPE)}>
              <View className="label">线型号</View>
              <View className="value">{selected_LINE_TYPE?.dictLabel || "选择球线型号"}</View>
              <AtIcon value={!showLINE_TYPE ? "chevron-down" : "chevron-right"} size={16}></AtIcon>
            </View>
            <View className={`row-select-list ${showLINE_TYPE ? "row-select-show" : ""}`}>
              {LINE_TYPE.map(item => (
                <View
                  className={`select-item ${
                    item.dictLabel === selected_LINE_TYPE?.dictLabel ? "select-item-active" : ""
                  }`}
                  key={item.dictLabel}
                  onClick={() => setSelected_LINE_TYPE(item)}
                >
                  {item.dictLabel}
                </View>
              ))}
            </View>
          </View>
        )}
        <View className="row">
          <View className="row-main" onClick={() => setShowLINE_POUND(!showLINE_POUND)}>
            <View className="label">磅数</View>
            <View className="value">{selected_LINE_POUND?.dictLabel || "选择磅数"}</View>
            <AtIcon value={!showLINE_POUND ? "chevron-down" : "chevron-right"} size={16}></AtIcon>
          </View>
          <View className={`row-select-list ${showLINE_POUND ? "row-select-show" : ""}`}>
            {LINE_POUND.map(item => (
              <View
                className={`select-item ${item.dictCode === selected_LINE_POUND?.dictCode ? "select-item-active" : ""}`}
                key={item.dictCode}
                onClick={() => setSelected_LINE_POUND(item)}
              >
                {item.dictLabel}
              </View>
            ))}
          </View>
        </View>
        {/* 取拍时间 */}
        <View className="row">
          <View className="row-main">
            <View className="label">取拍时间</View>
            <View className="value">
              <Picker mode="date" onChange={e => setDate(e.detail.value)}>
                {date ? date : <Text style={{ color: "#bbb" }}>请填写取拍时间</Text>}
              </Picker>
            </View>
            <AtIcon value="chevron-down" size={16}></AtIcon>
          </View>
        </View>
        {/* 备注 */}
        <View className="row">
          <View className="row-main">
            <View className="label">备注</View>
            <Input
              ref={remarkRef}
              maxlength={50}
              value={defaultRemark}
              placeholder="备注信息，限50字内"
              placeholderStyle="color: #BBBBBB;"
              className="value"
              onBlur={e => setDefaultRemark(e.detail.value)}
            ></Input>
          </View>
        </View>
      </View>
      {/* 费用 */}
      <View className="price">
        <View className="label">预计费用：</View>
        <View className="price-value">
          <Text className="price-unit">￥</Text>
          <Text>{(price * 100 + servicePrice * 100) / 100}</Text>
        </View>
        <View className="price-show-detail" onClick={() => setShowPriceDetail(!showPriceDetail)}>
          <PriceDetail
            show={showPriceDetail}
            productPrice={price}
            otherPrice={[{ key: "CODE_SERVICE_CHARGE", name: "服务费", value: servicePrice }]}
          ></PriceDetail>
          明细
        </View>
      </View>

      {/* 提交按钮 */}
      <Button className="submit-btn" onClick={checkSubmitData}>
        {ticketId ? "重新提交" : "提交"}
      </Button>

      {showPriceDetail && <View className="price-detail-mask" onClick={() => setShowPriceDetail(false)}></View>}
      {showSubmitDetail && (
        <SubmitDetail
          data={{
            userName: nameRef.current?.props.value || "",
            phone: phoneRef.current?.props.value || "",
            racketBrandName: selected_RACKET_BRAND?.dictLabel || "",
            threadingTypeName: selected_THREADING_TYPE?.dictLabel || "",
            lineTypeName: selected_LINE_TYPE?.dictLabel || "",
            linePoundName: selected_LINE_POUND?.dictLabel || "",
            userRemark: remarkRef.current?.props.value || "",
            date,
            price,
            servicePrice,
          }}
          submiteButtonText={ticketId ? "重新提交" : "确认提交"}
          onSubmit={onSubmit}
          onCancel={() => setShowSubmitDetail(false)}
        ></SubmitDetail>
      )}
    </View>
  )
}
